package util

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"

	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

type ArgsList struct {
	Resources []string
	Arguments []string
}

func InitConfig() string {
	path := os.Getenv("KUBECTL_CONFIG")
	if len(path) == 0 {
		panic("Please set the environment variable KUBECTL_CONFIG.")
	}

	return path
}

func InitArgs(arg string) []string {
	delimiter := []string{","}
	var resource []string

	if len(strings.TrimSpace(arg)) == 0 {
		return nil
	}

	for _, d := range delimiter {
		if strings.Contains(arg, d) {
			for _, a := range strings.Split(arg, d) {
				resource = append(resource, strings.TrimSpace(a))
			}
			if len(resource) > 0 {
				break
			}
		} else {
			resource = append(resource, strings.TrimSpace(arg))
		}
	}
	return resource
}

func SplitArgs(args []string) *ArgsList {
	var argsList ArgsList
	for n, a := range args {
		if n == 0 {
			argsList.Resources = InitArgs(a)
		}
		if n == 1 {
			argsList.Arguments = InitArgs(a)
		}
	}

	return &argsList
}

func IsBatch(ns string) {
	for {
		reader := bufio.NewReader(os.Stdin)
		fmt.Printf("Whether to delete all Pods in %s? yes/no: ", ns)
		input, err := reader.ReadString('\n')
		if err != nil {
			fmt.Printf("Fail is reason that, %s\n", err)
		}

		if strings.TrimSpace(input) == "yes" {
			return
		} else if input == "no" {
			os.Exit(1)
		}
	}
}

func NewConnect(c string) *kubernetes.Clientset {
	config, err := clientcmd.BuildConfigFromFlags("", c)
	if err != nil {
		panic(err.Error())
	}

	clientSet, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	return clientSet
}

func CalculateMaxLength(itemLengths []string) int {
	var maxLength int

	for _, item := range itemLengths {
		if len(item) > maxLength {
			maxLength = len(item)
		}
	}

	return maxLength
}

func FindMaxNumber(nsArgs []string) int {
	var intNumber []int
	var maxNumber int

	for _, ns := range nsArgs {
		n, _ := strconv.Atoi(ns)
		intNumber = append(intNumber, n)
	}

	for _, item := range intNumber {
		if maxNumber < item {
			maxNumber = item
		}
	}

	return maxNumber
}
